package com.hunlian.makelove;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.widget.Toast;

import com.hunlian.makelove.common.AppConfig;
import com.hunlian.makelove.common.AppUtils;
import com.hunlian.makelove.common.Printout;
import com.hunlian.makelove.net.ServiceInterfaceDef;
import com.hunlian.makelove.net.HttpPostUploadUtil;
import com.hunlian.makelove.net.IServiceReturnProcess;
import com.hunlian.makelove.tools.DeviceTools;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.lang.Thread.UncaughtExceptionHandler;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

/**
 * 应用崩溃捕获并记录日志
 * @author zealjiang
 * @time 2015年11月13日下午1:46:49
 */
public class AppUncaughtExceptionHandler implements UncaughtExceptionHandler{

    public static final String DIR = Environment.getExternalStorageDirectory()
            .getAbsolutePath() + "/hunlian/survey/log/";
    private static String TXTSuffix = getCurrentDateString() + ".txt";
    private Context mContext;

    
    
    
	public AppUncaughtExceptionHandler(Context context) {
		super();
		this.mContext = context;
	}


	@Override
	public void uncaughtException(Thread thread, Throwable ex) {
		Printout.println("伉俪网应用崩溃啦,请查看/survey/log/目录下的日志");
        String info = null;
        ByteArrayOutputStream baos = null;
        PrintStream printStream = null;
        try {
            baos = new ByteArrayOutputStream();
            printStream = new PrintStream(baos);
            ex.printStackTrace(printStream);
            ex.printStackTrace();
            byte[] data = baos.toByteArray();
            info = new String(data);
            data = null;
        } catch (Exception e) {
            e.printStackTrace();
           // Log.e("klw", e.getMessage(), ex);
            //Log.e("klw", info);
        } finally {
            try {
                if (printStream != null) {
                    printStream.close();
                }
                if (baos != null) {
                    baos.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
                //Log.e("klw", info, ex);
              //退出程序  
	          android.os.Process.killProcess(android.os.Process.myPid());  
	          System.exit(1);  
            }
        }
        writeErrorLog(info);
        
    }
	
	
	
	 /**
     * 向文件中写入错误信息
     * 
     * @param info
     */
    public static void writeErrorLog(String info) {
        File dir = new File(DIR);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        String channel = "";
        try {
            ApplicationInfo appInfo = AppApplication.getAppContext().getPackageManager().getApplicationInfo(AppApplication.getAppContext().getPackageName(),PackageManager.GET_META_DATA);
            channel =appInfo.metaData.getString("InstallChannel");
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        //Log.d(AppApplication.TAG, " channel == " + channel );

        String name = AppConfig.getInstance().getLoginedUserId()+"_"+TXTSuffix;
        File file = new File(dir, name);
        info = "时间："+getCurrentTimeString()+"\n"+
                "设备型号："+DeviceTools.getDeviceModel()+"\n"+
                "设备系统："+DeviceTools.getDeviceOs()+"\n"+
                "版本："+AppUtils.getVersionNameAndCode(AppApplication.getAppContext())+"\n" +
                "渠道："+channel+"\n"+ info;
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(file, true);
            fileOutputStream.write(info.getBytes());
            fileOutputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            sendErrorFile(file.getPath());
            killCurrentProcess();
        }
 
    }
 
    /**
     * 获取当前日期
     * 
     * @return
     */
    private static String getCurrentDateString() {
        String result = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd",
                Locale.getDefault());
        Date nowDate = new Date();
        result = sdf.format(nowDate);
        return result;
    }
    
    /**
     * 获取当前日期
     * 
     * @return
     */
    private static String getCurrentTimeString() {
        String result = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss  ",
                Locale.getDefault());
        Date nowDate = new Date();
        result = sdf.format(nowDate);
        return result;
    }

    /**
     * 发送错误文件
     * @author zealjiang
     * @time 2016/4/24 19:40
     */
    private static void sendErrorFile(String filePath){
        Map<String, String> fileMap = new HashMap<String, String>();
        Map<String, String> textMap = new HashMap<String, String>();
        textMap.put("functionId",ServiceInterfaceDef.FUNC_ID_LOG_ERROR);
        textMap.put("userId", AppConfig.getInstance().getLoginedUserId());
        fileMap.put("file", filePath);

        HttpPostUploadUtil.doPost(ServiceInterfaceDef.SERVICE_URL, textMap, fileMap,
                new IServiceReturnProcess() {
                    @Override
                    public void process(String serviceReturn) {
                        Printout.println("出错日志反馈 :" + serviceReturn);
                        try {
                            JSONObject obj = new JSONObject(serviceReturn);
                            String status = obj.getString("status");
                            if (status.equals("1")) {
                                Printout.println("出错日志反馈成功" + serviceReturn);
                                Toast.makeText(AppApplication.getAppContext(),
                                        "保存成功", Toast.LENGTH_SHORT).show();
                            } else {
                                String message = obj.getString("message");
                                System.out.println("message: "+message);
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                }
        );
    }

    private static void killCurrentProcess() {
        android.os.Process.killProcess(android.os.Process.myPid());
        System.exit(10);
    }
}
